import {
  NOT_LOADED,
  noSkip,
  isActive,
  noLoadError,
  isntLoaded,
  shouldBeActivity,
  shouldntBeActivity,
  isntActive,
  isLoaded
} from './apps.helper'
import {invoke} from '../navigations/invoke'

const APPS = [];

/**
 * 注册app
 * @param {string} appName 要注册的app名称
 * @param {Function<Promise>|Object} loadFunction app异步加载函数或app内容
 * @param {Function<boolean>} activityWhen 判断该app应该在何时被启动
 * @param {Object} customProps 自定义配置
 * return Promise
 */
export function registerApplication(appName, loadFunction, activityWhen, customProps = {}) {
  if (!appName || typeof appName !== 'string') {
    throw new Error('appName must be a non-empty string');
  }

  if (!loadFunction) {
    throw new Error('loadFunction must be a function or object');
  }

  if (typeof loadFunction !== 'function') {
    loadFunction = () => Promise.resolve(loadFunction);
  }

  if (typeof activityWhen !== 'function') {
    throw new Error('activity must b a function');
  }

  APPS.push({
    name: appName,
    loadFunction,
    activityWhen,
    customProps, // 会传给loadFunction作为参数,由用户自己定义
    status: NOT_LOADED
  });

  invoke()
}

export function getAppsToLoad(){
  return APPS.filter(noSkip).filter(noLoadError)
    .filter(isntLoaded).filter(shouldBeActivity);
}

export function getAppsToUnmount(){
  return APPS.filter(noSkip).filter(isActive).filter(shouldntBeActivity);
}

export function getAppsToMount(){
  return APPS.filter(noSkip).filter(isLoaded).filter(isntActive).filter(shouldBeActivity);
}

// 获取当前已经被挂载的app
export function getMountedApps(){
  return APPS.filter(app => isActive(app));
}
